package com.danciyixue.boot.dcyx.service.impl;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.danciyixue.boot.core.security.util.SecurityUtils;
import com.danciyixue.boot.dcyx.model.form.UserWordStatusUpdateForm;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.danciyixue.boot.dcyx.mapper.UserWordStatusMapper;
import com.danciyixue.boot.dcyx.service.UserWordStatusService;
import com.danciyixue.boot.dcyx.service.WordsService;
import com.danciyixue.boot.dcyx.model.entity.UserWordStatus;
import com.danciyixue.boot.dcyx.model.entity.Words;
import com.danciyixue.boot.dcyx.model.form.UserWordStatusForm;
import com.danciyixue.boot.dcyx.model.form.UserWordStatusUpdateForm;
import com.danciyixue.boot.dcyx.model.query.UserWordStatusQuery;
import com.danciyixue.boot.dcyx.model.vo.UserWordStatusVO;
import com.danciyixue.boot.dcyx.converter.UserWordStatusConverter;
import com.danciyixue.boot.core.security.util.SecurityUtils;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.time.LocalDateTime;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;

/**
 * 用户单词学习状态服务实现类
 *
 * @author youlaitech
 * @since 2025-06-24 15:50
 */
@Service
@DS("dcyx")
@RequiredArgsConstructor
public class UserWordStatusServiceImpl extends ServiceImpl<UserWordStatusMapper, UserWordStatus> implements UserWordStatusService {

    private final UserWordStatusConverter userWordStatusConverter;
    private final WordsService wordsService;

    /**
    * 获取用户单词学习状态分页列表
    *
    * @param queryParams 查询参数
    * @return {@link IPage<UserWordStatusVO>} 用户单词学习状态分页列表
    */
    @Override
    public IPage<UserWordStatusVO> getUserWordStatusPage(UserWordStatusQuery queryParams) {
        Page<UserWordStatusVO> pageVO = this.baseMapper.getUserWordStatusPage(
                new Page<>(queryParams.getPageNum(), queryParams.getPageSize()),
                queryParams
        );
        return pageVO;
    }
    
    /**
     * 获取用户单词学习状态表单数据
     *
     * @param id 用户单词学习状态ID
     * @return 用户单词学习状态表单数据
     */
    @Override
    public UserWordStatusForm getUserWordStatusFormData(Long id) {
        UserWordStatus entity = this.getById(id);
        return userWordStatusConverter.toForm(entity);
    }
    
    /**
     * 新增用户单词学习状态
     *
     * @param formData 用户单词学习状态表单对象
     * @return 是否新增成功
     */
    @Override
    public boolean saveUserWordStatus(UserWordStatusForm formData) {
        UserWordStatus entity = userWordStatusConverter.toEntity(formData);
        return this.save(entity);
    }
    
    /**
     * 更新用户单词学习状态
     *
     * @param id   用户单词学习状态ID
     * @param formData 用户单词学习状态表单对象
     * @return 是否修改成功
     */
    @Override
    public boolean updateUserWordStatus(Long id,UserWordStatusForm formData) {
        UserWordStatus entity = userWordStatusConverter.toEntity(formData);
        return this.updateById(entity);
    }
    
    /**
     * 删除用户单词学习状态
     *
     * @param ids 用户单词学习状态ID，多个以英文逗号(,)分割
     * @return 是否删除成功
     */
    @Override
    public boolean deleteUserWordStatuss(String ids) {
        Assert.isTrue(StrUtil.isNotBlank(ids), "删除的用户单词学习状态数据为空");
        // 逻辑删除
        List<Long> idList = Arrays.stream(ids.split(","))
                .map(Long::parseLong)
                .toList();
        return this.removeByIds(idList);
    }


    /**
     * 新增OR修改用户单词学习状态
     * formData 携带了 wordId, learned
     * 1. 先查后改，如果查到则修改、如果未查到则新增
     *  1. 查询，根据 userId、wordId， 查询 user_word_status 表，查出单个记录 user_word_status entity 类对象；
     *  2. 修改，learned 字段；
     * 2. 插入，补全 user_word_status 类对象的其他字段，插入 user_word_status 表；
     *
     * @param formData
     * @return
     */
    @Override
    public boolean saveOrUpdateUserWordStatus(UserWordStatusUpdateForm formData) {
        // 参数校验
        Assert.notNull(formData, "表单数据不能为空");
        Assert.notNull(formData.getWordId(), "单词ID不能为空");

        // 获取当前登录用户ID
        Long userId = SecurityUtils.getUserId();
        Assert.notNull(userId, "用户未登录");

        // 1. 根据 userId 和 wordId 查询现有记录
        UserWordStatus existingStatus = this.baseMapper.findByUserIdAndWordId(userId, formData.getWordId());

        if (existingStatus != null) {
            // 2. 如果记录存在，则更新 learned 字段和相关统计信息
            existingStatus.setLearned(formData.getLearned());
            existingStatus.setLastStudyAt(LocalDateTime.now());

            // 更新学习次数
            if (existingStatus.getStudyCount() == null) {
                existingStatus.setStudyCount(1);
            } else {
                existingStatus.setStudyCount(existingStatus.getStudyCount() + 1);
            }

            // learned 根据为 1 新增正确次数；
            // learned 为 0， 新增错误次数；
            if (formData.getLearned() == 1) {
                existingStatus.setCorrectCount(existingStatus.getCorrectCount() + 1);
            } else {
                existingStatus.setErrorCount(existingStatus.getErrorCount() + 1);
            }

            return this.updateById(existingStatus);
        } else {
            // 3. 如果记录不存在，则新增记录，需要补全其他字段
            // 根据 wordId 查询单词信息，获取 unitName、programId、seriesId
            Words word = wordsService.getById(formData.getWordId());
            Assert.notNull(word, "单词信息不存在");

            // 创建新的用户单词学习状态记录
            UserWordStatus newStatus = new UserWordStatus();
            newStatus.setUserId(userId);
            newStatus.setWordId(formData.getWordId());
            newStatus.setLearned(formData.getLearned());
            newStatus.setUnitName(word.getUnitName());
            newStatus.setProgramId(word.getProgramId());
            newStatus.setSeriesId(word.getSeriesId());
            newStatus.setStudyCount(1);
            if (formData.getLearned() == 1) {
                newStatus.setCorrectCount(1);
                newStatus.setErrorCount(0);
            } else {
                newStatus.setCorrectCount(0);
                newStatus.setErrorCount(1);
            }
            newStatus.setLastStudyAt(LocalDateTime.now());
            return this.save(newStatus);
        }
    }

}
